package com.ruoyi.web.controller.bmxt;
import com.ruoyi.bmxt.domain.BmFiles;
import com.ruoyi.bmxt.domain.BmSpecialtyFee;
import com.ruoyi.bmxt.domain.BmStudent;
import com.ruoyi.bmxt.domain.ui.FileZipDto;
import com.ruoyi.bmxt.domain.web.SpecialtyDto;
import com.ruoyi.bmxt.mapper.BmSpecialtyFeeMapper;
import com.ruoyi.bmxt.service.IBmFilesService;
import com.ruoyi.bmxt.service.IBmSpecialtyFeeService;
import com.ruoyi.bmxt.service.IBmStudentService;
import com.ruoyi.bmxt.utils.LoginUserUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.bmxt.service.ITestService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.DownZipUtil;
import com.ruoyi.common.utils.file.FileUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * 非验证接口实现
 *
 * @author 魏建波
 * Date:  2023/2/17
 * Time:  19:07
 * @description
 */
@RestController
@RequestMapping("/noAuth/web")
public class NoAuthController  extends BaseController {
    @Autowired
    private IBmFilesService bmFilesService;

    @Autowired
    ITestService testService;

    @Autowired
    IBmSpecialtyFeeService specialtyFeeService;

    @Autowired
    private IBmStudentService bmStudentService;
    // 扫码报名
    // 获得学校列表
    @GetMapping("/school/list")
    public AjaxResult schoolList()
    {
        List<SpecialtyDto> childrenList = specialtyFeeService.selectSchoolChildList(1L);
        return success(childrenList);
    }
    // 获得资格证书专业列表
    @GetMapping("/qualificationCertificate/list")
    public AjaxResult qualificationCertificateList()
    {
        List<SpecialtyDto> childrenList = specialtyFeeService.selectSchoolChildList(2L);
        return success(childrenList);
    }
    @GetMapping("/school/getSpecialty/{specialtyFeeId}")
    public AjaxResult getSpecialty(@PathVariable("specialtyFeeId") String specialtyFeeId)
    {
        BmSpecialtyFee specialtyFee = specialtyFeeService.selectBmSpecialtyFeeByIdFromWeb(Long.parseLong(specialtyFeeId));
        return success(specialtyFee);
    }

    // 学生添加
    @PostMapping("/student/add")
    public AjaxResult add(BmStudent bmStudent) throws IOException, InvalidExtensionException {
        //todo 身份证不能重复  如果重复需要返回消息  0-信息未审核 请联系招生老师 2-审核资料有问题 需要重新提交申请
        int row = 0;
        if (UserConstants.NOT_UNIQUE.equals(bmStudentService.checkIdCardUnique(bmStudent)))
        {
            // 0未审核 1 审核通过 2 审核驳回
            if(bmStudent.getAuditStatus() == 0){
                return error("报名信息已存在，等待审核");
            }else if(bmStudent.getAuditStatus() == 2){
                // 执行修改操作
                // return toAjax(bmStudentService.updateBmStudent(bmStudent));
                return error("报名信息已存在，部分信息不完整，请联系招生老师！");
            }

        }
        return toAjax(bmStudentService.insertBmStudentByWeb(bmStudent));
    }
    // 前端学生信息修改接口
    @PostMapping("/student/update")
    public AjaxResult update(BmStudent bmStudent) throws IOException, InvalidExtensionException {
        return toAjax(bmStudentService.updateBmStudent(bmStudent)); // 直接调用学生修改接口
    }
    // 根据学生身份证查询学生
    @GetMapping("/student/getByCardIdAndProjectId")
    public AjaxResult getByCardIdAndProjectId(@RequestParam(name = "idCard") String idCard,
                                  @RequestParam(name = "projectId") Long projectId)
    {
        BmStudent student = bmStudentService.selectBmStudentByCardIdAndProjectId(idCard,projectId);
        return success(student);
    }

    @DeleteMapping("/student/deleteFile/{fileIds}")
    public AjaxResult removeStudentFile(@PathVariable Long[] fileIds)
    {
        return toAjax(bmFilesService.deleteBmFilesByFileIds(fileIds));
    }

    /**
     * 修改学生上传文件接口
     * @param bmFiles
     * @return
     * @throws IOException
     * @throws InvalidExtensionException
     */
    // 学生和管理端  单个文件上传接口  此处没有日志  需要填写   学生Id  文件类型Id   文件信息列表
    @PostMapping("/addStudentFileUpload")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学生Id", dataType = "String", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "fileTypeId", value = "文件类型", dataType = "String", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "files", value = "上传文件列表", dataType = "MultipartFile", dataTypeClass = MultipartFile.class, required = true),
    })
    public AjaxResult addStudentFileUpload(BmFiles bmFiles) throws IOException, InvalidExtensionException {
        return success(bmFilesService.addStudentFileUpload(bmFiles));
    }

    /*// zip资料下载 不好使  废弃
    @GetMapping("/student/createFileByUser")
    public void createFileByUser(HttpServletResponse response, FileZipDto fileZipDto) throws Exception {
        String zipPath = bmStudentService.createFileByUser(fileZipDto);
        DownZipUtil.exportZip(response,zipPath, "文件资料");
        // 删除文件
        // DownZipUtil.deleteDirectory(new File(zipPath));
    }*/

    /*
    // 好使的
    @RequestMapping(value = "/student/createFileByUser", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadFile(FileZipDto fileZipDto)
            throws Exception {
        String zipPath = bmStudentService.createFileByUser(fileZipDto);
        FileSystemResource file = new FileSystemResource(zipPath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }*/

    @RequestMapping(value="/student/createFileByUser", method=RequestMethod.GET)
    public void getDownload(HttpServletRequest request, HttpServletResponse response,FileZipDto fileZipDto) throws Exception {
        String fullPath = bmStudentService.createFileByUser(fileZipDto);
        File downloadFile = new File(fullPath);

        ServletContext context = request.getServletContext();

        // get MIME type of the file
        String mimeType = context.getMimeType(fullPath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
            System.out.println("context getMimeType is null");
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",
                URLEncoder.encode(downloadFile.getName()));
        response.setHeader(headerKey, headerValue);

        // Copy the stream to the response's output stream.
        try {
            InputStream myStream = new FileInputStream(fullPath);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }

        downloadFile.delete();
    }


}
